#include <openssl/aes.h>

#include "tool.hpp"

void aes_cbc_dec(uint8_t* key, uint8_t* iv, uint8_t* in, uint32_t len, uint8_t* out)
{
	AES_KEY aes_key;

	AES_set_decrypt_key(key, 128, &aes_key);
	AES_cbc_encrypt(in, out, len, &aes_key, iv, AES_DECRYPT);
}

void aes_cbc_enc(uint8_t *key, uint8_t *iv, uint8_t *in, uint32_t len, uint8_t *out)
{
	AES_KEY aes_key;

	AES_set_encrypt_key(key, 128, &aes_key);
	AES_cbc_encrypt(in, out, len, &aes_key, iv, AES_ENCRYPT);
}

uint16_t get16(ifstream& stream)
{
	char temp[sizeof(uint16_t)];
	stream.read(temp, sizeof(temp));
	return be16toh(*reinterpret_cast<uint16_t*>(temp));
}

uint32_t get32(ifstream& stream)
{
	char temp[sizeof(uint32_t)];
	stream.read(temp, sizeof(temp));
	return be32toh(*reinterpret_cast<uint32_t*>(temp));
}

uint64_t get64(ifstream& stream)
{
	char temp[sizeof(uint64_t)];
	stream.read(temp, sizeof(temp));
	return be64toh(*reinterpret_cast<uint64_t*>(temp));
}

uint32_t add_padding(uint32_t value, uint32_t padding)
{
	return -(-value & -padding);
}
